# -*- coding: utf-8 -*-
from src.helper.id import IDHelper
from src.handler.event import EventHandler
from src.event.entity import EntityCollisionEvent
from pymunk import Vec2d
import pygame, pymunk

class Entity:

    name = "entity"

    def __init__(self):
        self.x = None
        self.y = None
        self.width = 0
        self.height = 0
        self.motionX = 0
        self.motionY = 0
        self.friction = 0.0
        self.mass = 1.0
        self.collision = False
        self.influence = True
        self.world = None
        self.shape = None
        self.id = IDHelper.getUniqueID("entity")

    def onClick(self, x, y):
        print("clicked on entity " + str(self))
        return False

    def onCollision(self, entity):
        EventHandler.post(EntityCollisionEvent(self, entity))

    def onSpawn(self):
        self.onLoad()

    def onDespawn(self):
        if self.shape is not None:
            self.world.space.remove(self.shape)
            del self.shape
            self.shape = None
        
    def onLoad(self):
        if self.influence:
            moment = pymunk.moment_for_box(self.mass, self.width, self.height)
            body = pymunk.Body(self.mass, moment)
            body.position = Vec2d(self.x, self.y)
            self.shape = pymunk.Poly.create_box(body, (self.width, self.height))
            self.shape.friction = self.friction
            self.shape.collision_type = 0
            self.shape.entity = self
            self.world.space.add(body, self.shape)
            if self.collision is False:
                self.shape.sensor = True

    def update(self):
        if self.shape is not None:
            self.x, self.y = self.shape.body.position
            self.shape.body.reset_forces()
            self.shape.body.apply_force(Vec2d(self.motionX, self.motionY))
        self.motionX = 0
        self.motionY = 0

    def move(self, x, y):
        self.motionX += x
        self.motionY += y
        
    def moveTo(self, x, y):
        target = Vec2d(x, y) - Vec2d(self.x, self.y)
        target.normalize_return_length()
        self.motionX += target.x * 100
        self.motionY += target.y * 100


    def readFromPSO(self, pso):
        self.x = pso.get("x")
        self.y = pso.get("y")
        self.id = pso.get("id")
        self.name = pso.type

    def writeToPSO(self, pso):
        pso.set("x", self.x)
        pso.set("y", self.y)
        pso.set("id", self.id)
        pso.type = self.name

    def render(self, client, viewport):
        if client.debug:
            pygame.draw.rect(client.window.surface, pygame.Color(255, 0, 0, 0), pygame.Rect((self.x - viewport.x) * 64, (self.y - viewport.y) * 64, 64 * self.width, 64 * self.height), 1)
